<template>
	<view class="container">
		<!-- 清空按钮 - 固定顶部 -->
		<view class="clear-cart-bar" v-if="cartItemCount > 0">
			<text class="clear-cart-btn" @click="clearCart">清空</text>
		</view>
		
		<!-- 加载状态 -->
		<view v-if="loading" class="loading-container">
			<text class="loading-text">加载中...</text>
		</view>
		
		<!-- 空状态 -->
		<view v-else-if="cartItems.length === 0" class="empty-container">
			<text class="empty-text">购物车是空的</text>
			<view class="empty-btn" @click="goToShoppingMall">
				<text class="empty-btn-text">去逛逛</text>
			</view>
		</view>
		
		<!-- 购物车商品列表 -->
		<view v-else class="cart-list">
			<view 
				class="cart-item" 
				v-for="(item, index) in cartItems" 
				:key="index"
			>
				<view class="check-box" :class="{ active: item.selected }" @click="toggleItemSelection(item.id)">
					<text v-if="item.selected" class="check-icon">✓</text>
				</view>
				<image class="cart-item-image" v-if="item.image" :src="item.image" mode="aspectFill"></image>
				<image class="cart-item-image" style="border:1px solid #f0f0f0;" v-else src="../common/images/noImage.png" mode="aspectFill"></image>
				<view class="cart-item-info">
					<text class="cart-item-name">{{ item.name }}</text>
					<text class="cart-item-costPrice" v-if="item.costPrice">¥{{ item.costPrice }}</text>
					<text class="cart-item-price">¥{{ item.price }}</text>
				</view>
				<view class="cart-quantity-selector">
					<view class="cart-quantity-btn decrease" @click="decreaseQuantity(item.id)">
					</view>
					<input
						class="cart-quantity-input"
						type="number"
						v-model="inputValues[item.id]"
						@input="handleQuantityInput(item.id, $event)"
						@blur="handleQuantityBlur(item.id)"
						:maxlength="getStockDigits(item.id)"
					/>
					<view class="cart-quantity-btn increase" @click="increaseQuantity(item.id)">
					</view>
				</view>
			</view>
		</view>
		
		<!-- 底部结算栏 -->
		<view class="cart-footer">
			<view class="cart-summary">
				<view class="check-box" :class="{ active: isAllSelected }" @click="toggleSelectAll">
					<text v-if="isAllSelected" class="check-icon">✓</text>
				</view>
				<text class="summary-text">合计: ¥{{ cartTotal }}</text>
			</view>
			<view class="cart-checkout-btn" @click="goToCheckout">
				<text class="cart-checkout-text">去结算</text>
			</view>
		</view>
		
		<!-- 底部导航栏 -->
		<view class="bottom-nav">
			<view class="nav-item" @click="goToShoppingMall">
				<text class="nav-icon">
					<image src="../common/images/index1.png" mode="aspectFill"></image>
				</text>
				<text class="nav-label">首页</text>
			</view>
			<view class="nav-item active">
				<text class="nav-icon">
					<image src="../common/images/car2.png" mode="aspectFill"></image>
				</text>
				<text class="nav-label">购物车</text>
				<view v-if="cartItemCount > 0" class="nav-badge">
					<text class="nav-badge-text">{{ cartItemCount }}</text>
				</view>
			</view>
			<view class="nav-item" @click="goToOrderList">
				<text class="nav-icon">
					<image src="../common/images/order1.png" mode="aspectFill"></image>
				</text>
				<text class="nav-label">订单</text>
			</view>
			<view class="nav-item" @click="goToShoppingOrderList">
				<text class="nav-icon">
					<image src="../common/images/order1.png" mode="aspectFill"></image>
				</text>
				<text class="nav-label">交款订单</text>
			</view>
		</view>
		
		<!-- 底部指示器 -->
		<view class="home-indicator"></view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			cart: {},
			inputValues: {}, // v-model 输入缓存
			selectedItems: {}, // 选中的商品 {productId: true/false}
			products: {},
			loading: false,
			updateCartTimers: {} // 防抖定时器对象 {productId: timer}
		}
	},
	onLoad() {
		// 页面初始化，不在这里加载数据，统一在 onShow 中加载
	},
	onShow() {
		// 页面显示时加载购物车数据（包括首次进入和从其他页面返回）
		this.loadCartData()
	},
	computed: {
		cartItems() {
			const items = []
			for (let productId in this.cart) {
				if (this.cart[productId] > 0 && this.products[productId]) {
					items.push({
						...this.products[productId],
						quantity: this.cart[productId],
						selected: this.selectedItems[productId] !== false // 默认为选中状态
					})
				}
			}
			return items
		},
		cartTotal() {
			let total = 0
			for (let item of this.cartItems) {
				if (item.selected) {
					total += item.price * item.quantity
				}
			}
			return total
		},
		cartItemCount() {
			let count = 0
			for (let quantity of Object.values(this.cart)) {
				count += quantity
			}
			return count
		},
		isAllSelected() {
			if (this.cartItems.length === 0) return false
			return this.cartItems.every(item => item.selected)
		}
	},
	methods: {
		// 加载购物车数据
		loadCartData() {
			this.loading = true
			
			this.$u.api.shopcart.list().then(res => {
				this.loading = false
				
				if (res && res.list) {
					// 清空现有数据
					this.cart = {}
					this.products = {}
					
					// 处理购物车数据
					res.list.forEach(item => {
						// 设置购物车数量
						this.$set(this.cart, item.productId, item.quantity)
						this.$set(this.inputValues, item.productId, String(item.quantity || 0))
						
						// 设置商品信息
						this.$set(this.products, item.productId, {
							id: item.productId,
							name: item.productName || item.name || '',
							image: item.productImage || item.image || '',
							price: item.productPrice || item.price || 0,
							stock: item.productStock || item.stock || 0,
							costPrice: item.productCostPrice || 0
						})
					})
					
					console.log('购物车数据加载成功:', this.cart)
					console.log('商品信息:', this.products)
				} else {
					this.cart = {}
					this.products = {}
				}
			}).catch(err => {
				this.loading = false
				console.error('获取购物车数据失败:', err)
				uni.showToast({
					title: '获取购物车数据失败',
					icon: 'none'
				})
			})
		},
		
		increaseQuantity(productId) {
			console.log('增加商品数量:', productId)
			
			// 获取当前商品信息
			const product = this.products[productId]
			const currentQuantity = this.cart[productId] || 0
			const maxStock = Number(product.stock) || 0
			
			// 检查是否超过库存
			if (currentQuantity >= maxStock) {
				uni.showToast({
					title: `库存不足，最多只能选择${maxStock}件`,
					icon: 'none'
				})
				return
			}
			
			// 先更新本地购物车数据
			const newQuantity = currentQuantity + 1
			this.$set(this.cart, productId, newQuantity)
			this.$set(this.inputValues, productId, String(newQuantity))
			console.log('购物车状态:', this.cart)
			
			// 调用防抖更新接口
			this.updateCartDebounce(productId, newQuantity)
		},
		decreaseQuantity(productId) {
			console.log('减少商品数量:', productId)
			if (this.cart[productId] && this.cart[productId] > 0) {
				const newQuantity = this.cart[productId] - 1
				
				// 先更新本地购物车数据
				if (newQuantity === 0) {
					this.$delete(this.cart, productId)
					this.$set(this.inputValues, productId, '0')
				} else {
					this.$set(this.cart, productId, newQuantity)
					this.$set(this.inputValues, productId, String(newQuantity))
				}
				console.log('购物车状态:', this.cart)
				
				// 调用防抖更新接口
				this.updateCartDebounce(productId, newQuantity)
			}
		},
		// 手动输入数量（输入阶段夹紧并同步本地与服务器，使用事件值防止读取旧值）
		handleQuantityInput(productId, e) {
			let val = (e && e.detail && e.detail.value != null) ? String(e.detail.value) : (this.inputValues[productId] != null ? String(this.inputValues[productId]) : '')
			val = val.replace(/[^\d]/g, '')
			let num = val === '' ? 0 : parseInt(val, 10)
			if (isNaN(num)) num = 0
			const product = this.products[productId] || {}
			const maxStock = Number(product.stock) || 0
			if (num > maxStock) num = maxStock
			if (num < 0) num = 0
			this.$set(this.inputValues, productId, String(num))
			this.$set(this.cart, productId, num)
			this.updateCartDebounce(productId, num)
		},
		// 失焦时再校验一次并同步
		handleQuantityBlur(productId) {
			let val = this.inputValues[productId] != null ? String(this.inputValues[productId]) : '0'
			val = val.replace(/[^\d]/g, '')
			let num = val === '' ? 0 : parseInt(val, 10)
			if (isNaN(num)) num = 0
			const product = this.products[productId] || {}
			const maxStock = Number(product.stock) || 0
			if (num > maxStock) num = maxStock
			if (num < 0) num = 0
			this.$set(this.inputValues, productId, String(num))
			this.$set(this.cart, productId, num)
			this.updateCartDebounce(productId, num)
		},
		// 根据库存位数限制输入长度
		getStockDigits(productId) {
			const product = this.products[productId] || {}
			const stock = Number(product.stock) || 0
			const digits = String(stock).length
			return digits > 0 ? digits : 3
		},
		
		// 防抖更新购物车接口
		updateCartDebounce(productId, quantity) {
			// 清除之前的定时器
			if (this.updateCartTimers[productId]) {
				clearTimeout(this.updateCartTimers[productId])
			}
			
			// 设置新的定时器，800ms后执行
			this.updateCartTimers[productId] = setTimeout(() => {
				this.updateCartToServer(productId, quantity)
			}, 800)
		},
		
		// 更新购物车到服务器
		updateCartToServer(productId, quantity) {
			console.log('调用购物车接口:', { productId, quantity })
			
			this.$u.api.shopcart.updateCart({
				productId: productId,
				quantity: quantity
			}).then(res => {
				console.log('购物车更新成功:', res)
				if (res && res.result === 'true') {
					// 接口调用成功
					console.log('购物车同步成功')
				} else {
					// 接口调用失败，给出提示
					uni.showToast({
						title: res.message || '购物车更新失败',
						icon: 'none'
					})
				}
			}).catch(err => {
				console.error('购物车更新失败:', err)
				uni.showToast({
					title: '购物车更新失败，请重试',
					icon: 'none'
				})
			})
		},
		goToCheckout() {
			// 只获取选中的商品
			const selectedItems = this.cartItems.filter(item => item.selected)
			
			if (selectedItems.length === 0) {
				uni.showToast({
					title: '请选择要购买的商品',
					icon: 'none'
				})
				return
			}
			
			uni.navigateTo({
				url: '/pages/inventoryManagement/confirmOrder?cart=' + JSON.stringify(selectedItems) + '&fromCart=true'
			})
		},
		goToShoppingMall() {
			uni.navigateTo({
				url: '/pages/inventoryManagement/shoppingMall'
			})
		},
		goToOrderList() {
			uni.navigateTo({
				url: '/pages/inventoryManagement/orderList'
			})
		},
		goToShoppingOrderList() {
			uni.navigateTo({
				url: '/pages/inventoryManagement/shoppingOrderList?byShop=1'
			})
		},
		toggleItemSelection(productId) {
			console.log('切换商品选择状态:', productId, '当前状态:', this.selectedItems[productId])
			// 如果当前状态是undefined，说明是默认选中状态，应该设为false
			const currentState = this.selectedItems[productId] !== false
			this.$set(this.selectedItems, productId, !currentState)
			console.log('切换后状态:', this.selectedItems[productId])
		},
		selectAllItems() {
			for (let item of this.cartItems) {
				this.$set(this.selectedItems, item.id, true)
			}
		},
		unselectAllItems() {
			for (let item of this.cartItems) {
				this.$set(this.selectedItems, item.id, false)
			}
		},
		toggleSelectAll() {
			if (this.isAllSelected) {
				// 如果全部选中，则取消全选
				this.unselectAllItems()
			} else {
				// 如果有未选中的，则全选
				this.selectAllItems()
			}
		},
		clearCart() {
			uni.showModal({
				title: '提示',
				content: '确定要清空购物车吗？',
				success: (res) => {
					if (res.confirm) {
						uni.showLoading({ title: '清空中...' })
						this.$u.api.shopcart.clear().then(res => {
							uni.hideLoading()
							if (res && res.result === 'true') {
								this.cart = {}
								this.products = {}
								this.selectedItems = {}
								this.$forceUpdate()
								uni.showToast({
									title: '购物车已清空',
									icon: 'success'
								})
							} else {
								uni.showToast({
									title: res.message || '清空失败',
									icon: 'none'
								})
							}
						}).catch(err => {
							uni.hideLoading()
							uni.showToast({
								title: '操作失败，请重试',
								icon: 'none'
							})
						})
					}
				}
			})
		}
	},
	onBackPress() {
		// 拦截返回按钮，返回到首页
		uni.reLaunch({
			url: '/pages/sys/home/index4'
		})
		return true
	},
	onUnload() {
		// 页面卸载时清除所有定时器
		for (let productId in this.updateCartTimers) {
			if (this.updateCartTimers[productId]) {
				clearTimeout(this.updateCartTimers[productId])
			}
		}
	}
}
</script>

<style scoped>
.container {
	background-color: #ffffff;
	display: flex;
	flex-direction: column;
	padding-bottom: 120px;
}

/* 购物车商品列表 */
.cart-list {
	flex: 1;
	padding: 20px;
	padding-top: 30px; /* 为固定顶部的清空按钮留出空间 */
}

.clear-cart-bar {
	position: fixed;
	top: 40px;
	left: 0;
	right: 0;
	height: 44px;
	background-color: #ffffff;
	display: flex;
	justify-content: flex-end;
	align-items: center;
	padding-right: 20px;
	z-index: 100;
}

/* #ifdef APP-PLUS */
.clear-cart-bar {
	top: 0px;
}
/* #endif */

.clear-cart-btn {
	font-size: 15px;
	color: #ff4069;
	font-weight: 500;
	padding: 5px 10px;
}

.cart-item {
	display: flex;
	align-items: center;
	padding: 15px 0;
	border-bottom: 1px solid #f8f8f8;
}

.check-box {
	width: 20px;
	height: 20px;
	border: 2px solid #ccc;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 10px;
}

.check-icon {
	font-size: 12px;
	color: #fff;
	font-weight: bold;
}

.cart-item-image {
	width: 50px;
	height: 50px;
	border-radius: 8px;
	margin-right: 10px;
	background-color: #f0f0f0;
}

.cart-item-info {
	flex: 1;
}

.cart-item-name {
	font-size: 14px;
	color: #333333;
	font-weight: bold;
	margin-bottom: 5px;
	display: block;
}
.cart-item-costPrice {
	font-size: 10px;
	color: #666666;
	text-decoration: line-through;
	display: block;
}

.cart-item-price {
	font-size: 14px;
	color: #ff4069;
	font-weight: bold;
}

.cart-quantity-selector {
	display: flex;
	align-items: center;
	gap: 8px;
}

.cart-quantity-btn {
	width: 20px;
	height: 20px;
	background-color: #ff4069;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	position: relative;
}

.cart-quantity-btn::before {
	content: '';
	position: absolute;
	width: 8px;
	height: 1px;
	background-color: #ffffff;
}

.cart-quantity-btn.decrease::before {
	/* 减号就是一条横线，不需要额外样式 */
	display: block;
}

.cart-quantity-btn.increase::after {
	content: '';
	position: absolute;
	width: 1px;
	height: 8px;
	background-color: #ffffff;
}

.cart-quantity-number {
	font-size: 12px;
	color: #333333;
	font-weight: bold;
	min-width: 20px;
	text-align: center;
}

.cart-quantity-input {
	width: 36px;
	height: 24px;
	line-height: 24px;
	background-color: #ffffff;
	border: 1px solid #f0f0f0;
	border-radius: 4px;
	text-align: center;
	font-size: 12px;
	color: #333333;
	font-weight: bold;
	padding: 0;
}

/* 底部结算栏 */
.cart-footer {
	position: fixed;
	bottom: 60px;
	left: 0;
	right: 0;
	height: 50px;
	background-color: #ffffff;
	border-top: 1px solid #f0f0f0;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 20px;
	z-index: 100;
}

.cart-summary {
	display: flex;
	align-items: center;
	gap: 8px;
}

.check-box.active {
	background-color: #ff4069;
	border: 2px solid #ff4069;
}

.summary-text {
	font-size: 16px;
	color: #ff4069;
	font-weight: bold;
}

.cart-checkout-btn {
	height: 40px;
	padding: 0 30px;
	background-color: #ff4069;
	border-radius: 20px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.cart-checkout-text {
	font-size: 16px;
	color: #ffffff;
	font-weight: bold;
}

/* 底部导航栏 */
.bottom-nav {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 60px;
	background-color: #ffffff;
	border-top: 1px solid #f0f0f0;
	display: flex;
	z-index: 100;
}

.nav-item {
	flex: 1;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	position: relative;
}

.nav-icon {
	font-size: 20px;
	color: #666666;
	display: flex;
	align-items: center;
	justify-content: center;
}

.nav-icon image {
	width: 25px;
	height: 25px;
}

.nav-label {
	font-size: 12px;
	color: #666666;
}

.nav-item.active .nav-icon {
	color: #ff4069;
}

.nav-item.active .nav-label {
	color: #ff4069;
}

.nav-badge {
	position: absolute;
	top: 5px;
	right: 20px;
	width: 16px;
	height: 16px;
	background-color: #ff4069;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
}

.nav-badge-text {
	font-size: 10px;
	color: #ffffff;
	font-weight: bold;
}

/* 底部指示器 */
.home-indicator {
	position: fixed;
	bottom: 10px;
	left: 50%;
	transform: translateX(-50%);
	width: 40px;
	height: 4px;
	background-color: #000000;
	border-radius: 2px;
}

/* 加载状态 */
.loading-container {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 100px 20px;
	padding-top: 144px; /* 为固定顶部留出空间 */
}

.loading-text {
	color: #999999;
	font-size: 14px;
}

/* 空状态 */
.empty-container {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	padding: 100px 20px;
	padding-top: 144px; /* 为固定顶部留出空间 */
}

.empty-text {
	color: #999999;
	font-size: 16px;
	margin-bottom: 30px;
}

.empty-btn {
	width: 200px;
	height: 45px;
	background-color: #ff4069;
	border-radius: 22px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.empty-btn-text {
	font-size: 16px;
	color: #ffffff;
	font-weight: bold;
}
</style>
